import requests
from bs4 import BeautifulSoup
# 获取菜谱分类
def getCategory():
    URL = 'https://www.xiachufang.com/category/'
    response = requests.get(URL)
    bs = BeautifulSoup(response.text,features = 'html.parser')
    listOne = bs.findAll('div',{'class':'cates-list'})
    rJson = {
        "child": []
    }
    for lo in listOne:
        # 第一类
        name0 = lo.find('h3',{'class':'font20'}).get_text()
        jsonO = {
            "name": name0,
            "child": []
        }
        listTwo = lo.findAll('h4',{'class':'font16'})
        for lt in listTwo:
            name1 = lt.get_text().strip().replace("\n", "")
            # 第二类
            jsonT = {
                "name": name1,
                "child": []
            }
            if lt.find('a'):
                src1 = lt.find('a')['href']
                jsonT["src"] = src1
            # 第三类
            listThree = lt.findNext('ul').findAll('li')
            for lth in listThree:
                name2 = lth.find('a').get_text()
                src2 = lth.find('a')['href']
                jsonT['child'].append({
                    "name": name2,
                    "src": src2
                })
            jsonO["child"].append(jsonT)
        rJson["child"].append(jsonO)
    return rJson
# 获取菜谱详情
def getDetail(id):
    URL = 'https://www.xiachufang.com/recipe/%s/'%id
    response = requests.get(URL)
    bs = BeautifulSoup(response.text, features='html.parser')
    rJson = {}
    rJson["name"] = bs.find('h1', {'itemprop': 'name'}).get_text().strip().replace("\n","")
    rJson["logo"] = bs.find('img', {'itemprop': 'image'})['src']
    if bs.find('div', {'itemprop': 'description'}):
        rJson["intro"] = bs.find('div', {'itemprop': 'description'}).get_text().strip().replace("\n","")
    rJson["need"] = []
    needs = bs.findAll('tr', {'itemprop': 'recipeIngredient'})
    for item in needs:
        text = item.find('td', {'class': 'name'}).get_text().strip().replace("\n","")
        ex = item.find('td', {'class': 'unit'}).get_text().strip().replace("\n","")
        rJson["need"].append({
            "text": text,
            "ex": ex
        })
    rJson["process"] = []
    process = bs.findAll('li', {'itemprop': 'recipeInstructions'})
    for item in process:
        text = item.find('p', {'class': 'text'}).get_text().strip().replace("\n","")
        processJson = {
            "text": text
        }
        if item.find('img'):
            processJson["img"] = item.find('img')['src']
        rJson["process"].append(processJson)
    if bs.find('div', {'class': 'tip'}):
        rJson["tips"] = bs.find('div', {'class': 'tip'}).get_text().strip().replace("\n","")
    return rJson
# 根据类别获取列表
def getCateList(id, page):
    URL = 'https://www.xiachufang.com/category/%s/?page=%s'%(id, page)
    return getContent(URL)
# 搜索后获取列表
def searchBywords(words, page):
    URL = 'https://www.xiachufang.com/search/?keyword=%s&page=%s'%(words, page)
    return getContent(URL)
# 本周推荐列表
def recommand(page):
    URL = 'https://www.xiachufang.com/explore/?page=%s'%page
    return getContent(URL)

def getContent(url):
    response = requests.get(url)
    bs = BeautifulSoup(response.text, features='html.parser')
    rJson = {}
    lis = bs.find('div', {'class': 'normal-recipe-list'}).find('ul', {'class': 'list'}).findAll('li')
    rJson = {
        "list": []
    }
    for item in lis:
        src = item.find('a')['href']
        img = item.find('a').find('img').get('data-src')
        info = item.find('div', {'class': 'info'})
        name = info.find('p', {'class': 'name'}).find('a').get_text().strip().replace("\n", "")
        intro = info.find('p', {'class': 'ing'}).get_text().strip().replace("\n", "")
        score = info.find('p', {'class': 'stats'}).find('span').get_text().strip().replace("\n", "")
        rJson["list"].append({
            "src": src,
            "img": img,
            "name": name,
            "intro": intro,
            "score": score
        })
    return rJson

def getKeywords():
    URL = 'https://www.xiachufang.com/'
    response = requests.get(URL)
    bs = BeautifulSoup(response.text, features='html.parser')
    rJson = {
        "data": []
    }
    menuList = bs.find('ul',{'class':'homepage-cats'}).findAll('li')
    for item in menuList:
        if item.find('span',{'class':'cat-name'}):
            name = item.find('span',{'class':'cat-name'}).get_text()
            rJson["data"].append(name)
    return rJson
if __name__ == '__main__':
    # getCategory()
    # getDetail(102311915)
    # print(getCateList('40077', 1))
    # print(searchBywords("红烧牛肉", 1))
    # print(recommand(1))
    getKeywords()